﻿using System.Configuration;
using System.ServiceProcess;
using System.Timers;
using Apollo.BulkImporter.WebServices;
using LumenWorks.Framework.IO.Csv;
using System;
using System.IO;

namespace Apollo.BulkImporter
{
    public partial class BulkImporter : ServiceBase
    {
        protected Timer timer;
        protected bool isProcessingAnImport = false;

        public BulkImporter()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            int elapsed_minutes = 0;

            if (!int.TryParse(ConfigurationManager.AppSettings["apollo.bulk_import.elapsed_minutes"], out elapsed_minutes))
                elapsed_minutes = 30;

            #warning check if the folder exists

            timer = new Timer(60000 * elapsed_minutes); // this is in miliseconds

            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

        protected override void OnStop()
        {
            timer.Stop();
        }

        protected void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isProcessingAnImport) return; // wait the next elapsed

            // first try: without threads
            BulkImportService service = this.GetWebService();

            foreach (BulkImport import in service.GetPendingImports()) {
                if (service.BeginImport(import) == BulkImportState.Pending) { 
                    // go Captain Planet
                    CsvReader csvReader;

                    try {
                        string filePath = import.FilePath.Replace("~/", 
                            ConfigurationManager.AppSettings["apollo.bulk_import.file_path"]);

                        if(!File.Exists(filePath)) {
                            import.State = BulkImportState.Failed;
                            import.FailureReason = "No file was found at address: \"" + filePath + "\"";

                            service.RollbackImport(import);
                        }

                        csvReader = new CsvReader(new StreamReader(filePath), true);
 
                        foreach(string[] row in csvReader)
                            service.ImportRow(import, row);
                    }
                    catch (Exception ex) {
                        import.State = BulkImportState.Failed;
                        import.FailureReason = ex.Message;

                        service.RollbackImport(import);
                    }
                }
            }
        }

        protected BulkImportService GetWebService() {
            BulkImportService service = new BulkImportService();
            service.Credentials = new System.Net.NetworkCredential(
                ConfigurationManager.AppSettings["apollo.bulk_import.username"],
                ConfigurationManager.AppSettings["apollo.bulk_import.password"]);

            return service;
        }

    }
}
